<template>
  <Card
    title="草稿箱"
    :bordered="false"
    v-loading="loading"
    :head-style="{ padding: '0' }"
    :body-style="{ padding: '10px 0' }"
  >
    <div style="background-color: #e7eff6" class="flex justify-start gap-2 p-8px">
      <Dropdown :trigger="['hover']" :overlayStyle="{ width: '78px', minWidth: '78px' }">
        <Button type="primary">
          <template #icon>
            <DownOutlined />
          </template>
          选择
        </Button>
        <template #overlay>
          <Menu>
            <MenuItem @click.stop="handleSelect('全选')"> 全选 </MenuItem>
            <MenuItem @click.stop="handleSelect('不选')"> 不选 </MenuItem>
            <MenuItem @click.stop="handleSelect('未读')"> 未读 </MenuItem>
            <MenuItem @click.stop="handleSelect('已读')"> 已读 </MenuItem>
          </Menu>
        </template>
      </Dropdown>
      <Button type="primary" @click="handleRefresh">
        <template #icon>
          <RedoOutlined />
        </template>
        刷新
      </Button>
      <Button @click="handleDeleteBatch">
        <template #icon>
          <DeleteOutlined style="color: red" />
        </template>
        删除
      </Button>
      <Button type="primary" @click="handleTransmit">
        <template #icon>
          <SendOutlined />
        </template>
        转发
      </Button>
      <Dropdown :trigger="['hover']" :overlayStyle="{ width: '96px', minWidth: '96px' }">
        <Button type="primary">
          <template #icon>
            <SwapOutlined />
          </template>
          移动到
        </Button>
        <template #overlay>
          <Menu>
            <MenuItem @click.stop="handleMoveData(3)"> 发件箱 </MenuItem>
            <MenuItem @click.stop="handleMoveData(0)"> 草稿箱 </MenuItem>
            <MenuItem @click.stop="handleMoveData(2)"> 删除 </MenuItem>
          </Menu>
        </template>
      </Dropdown>
    </div>
    <BasicTable @register="registerTable" class="custom-table">
      <template #subject="{ text, record }">
        <a-button type="link" @click="handleEdit(record)">
          {{ text }}
        </a-button>
      </template>
      <template #sender="{ text, record }">
        <a-button type="link" @click="handleEdit(record)">
          {{ text }}
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
              tooltip: '编辑',
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                placement: 'leftBottom',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
  </Card>
</template>
<script lang="ts">
  import { defineComponent, h, ref, inject } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { columns, searchFormSchema } from './draftbox.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Card, Button, Dropdown, Menu } from 'ant-design-vue';
  import { RedoOutlined, DeleteOutlined, SendOutlined, DownOutlined } from '@ant-design/icons-vue';
  import { getEmailListDraft, getEmailDelMail, getEmailMoveMail } from '/@/api/email/externalEmail';

  export default defineComponent({
    name: 'DraftboxList',
    components: {
      BasicTable,
      TableAction,
      Card,
      Button,
      RedoOutlined,
      DeleteOutlined,
      SendOutlined,
      Dropdown,
      Menu,
      MenuItem: Menu.Item,
      DownOutlined,
    },
    emits: ['handle-transmit', 'handle-edit'],
    setup(_, { emit }) {
      const loading = ref(false);
      const { createMessage, createConfirm } = useMessage();
      const internalEmail = inject('internalEmail') as any;
      const [
        registerTable,
        { reload, getSelectRowKeys, getSelectRows, getDataSource, setSelectedRowKeys },
      ] = useTable({
        title: '',
        api: getEmailListDraft,
        columns,
        formConfig: {
          labelWidth: 0,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
          actionColOptions: {
            sm: 8,
            md: 8,
            lg: 6,
            xl: 5,
            xxl: 3,
          },
        },
        searchInfo: {
          op: 'search',
        }, //额外的参数
        beforeFetch: (info) => {
          if (internalEmail.emailInfo.value.id != -1) {
            info.emailId = internalEmail.emailInfo.value.id;
          }
          return info;
        },
        rowSelection: {
          type: 'checkbox',
          columnWidth: 40,
        },
        clickToRowSelect: false,
        useSearchForm: true,
        showTableSetting: false,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        rowKey: 'id',
        canResize: false,
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
      });

      async function handleDelete(record: Recordable) {
        await getEmailDelMail({ emailId: internalEmail.emailInfo.value.id, ids: record.id });
        handleSuccess();
      }

      async function handleDeleteBatch() {
        let checkes = getSelectRowKeys();
        if (checkes.length == 0) {
          createMessage.warn('删除数据不能为空');
          return;
        }

        createConfirm({
          iconType: 'warning',
          title: () => h('span', '您确定删除么？'),
          onOk: async () => {
            let ids = checkes.join(',');
            try {
              loading.value = true;
              await getEmailDelMail({ emailId: internalEmail.emailInfo.value.id, ids: ids });
              handleSuccess();
            } catch (error) {
            } finally {
              loading.value = false;
            }
          },
        });
      }
      function handleSuccess() {
        reload();
      }

      function handleEdit(record: Recordable) {
        emit('handle-edit', record);
      }

      //选择
      const handleSelect = (type) => {
        switch (type) {
          case '全选':
            const data1 = getDataSource();
            const keys1 = data1.map((item) => item.id);
            setSelectedRowKeys(keys1);
            break;
          case '不选':
            setSelectedRowKeys([]);
            break;
          case '未读':
            const data2 = getDataSource();
            const keys2 = data2.filter((item) => !item.isReaded).map((el) => el.id);
            setSelectedRowKeys(keys2);
            break;
          case '已读':
            const data3 = getDataSource();
            const keys3 = data3.filter((item) => !!item.isReaded).map((el) => el.id);
            setSelectedRowKeys(keys3);
            break;
        }
      };
      //移动到
      const handleMoveData = async (type) => {
        let checkes = getSelectRowKeys();
        if (checkes.length == 0) {
          createMessage.warn('请选择数据');
          return;
        }
        try {
          const params = {
            emailId: internalEmail.emailInfo.value.id,
            sender: '',
            ids: checkes.join(','),
            box: type,
          };
          loading.value = true;
          await getEmailMoveMail(params);
          loading.value = false;
          handleRefresh();
        } catch (error) {
          loading.value = false;
        }
      };

      //刷新
      const handleRefresh = () => {
        setSelectedRowKeys([]);
        reload();
      };

      //转发
      const handleTransmit = () => {
        const data = getSelectRows();
        if (data.length != 1) {
          createMessage.warn('请选择一条数据');
          return;
        }
        emit('handle-transmit', data[0]);
      };

      return {
        registerTable,
        handleDelete,
        handleSuccess,
        handleDeleteBatch,
        handleEdit,
        handleRefresh,
        handleTransmit,
        loading,
        handleMoveData,
        handleSelect,
      };
    },
  });
</script>

<style lang="less" scoped>
  :deep(.ant-card-head-title) {
    padding: 8px 8px 0;
  }
  .custom-table {
    padding: 0;
    margin-top: 10px;
    :deep(.ant-table-wrapper) {
      padding: 0;
    }
  }
</style>
